package data;

import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import android.app.Activity;

/**
 * Adds a new item to a database.
 * 
 * @author Kelsey
 */
public class AddItem extends DBBooleanTask<Item> {

	/**
	 * Constructs an object that tries to add an item to a database
	 * 
	 * @param activity
	 *            the active Android activity
	 * @param data
	 *            the item to be added
	 * @throws DBInterfaceError
	 */
	public AddItem(Activity activity, Item data) throws DBInterfaceError {
		super(activity, data);
	}

	/**
	 * Attempt to add the given item to a database
	 * 
	 * @param item
	 *            the item to add
	 * @return whether or not the item was successfully added
	 */
	@Override
	protected boolean task(Item item) {
		boolean success = true;

		try {
			PreparedStatement addAccountQuery;
			addAccountQuery = conn
					.prepareStatement("INSERT INTO item_old (name, description, status, category, type, picture, dateEntered, accountName, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
			addAccountQuery.setString(1, item.getName());
			addAccountQuery.setString(2, item.getDescription());
			addAccountQuery.setString(3, item.getStatus().toString());
			addAccountQuery.setString(4, item.getCategory().toString());
			addAccountQuery.setString(5, item.getType().toString());
			addAccountQuery.setBlob(6, (Blob) item.getPicture());
			addAccountQuery.setTimestamp(7, new java.sql.Timestamp(item
					.getDateEntered().getTime()));
			addAccountQuery.setString(8, item.getAccountName());
			addAccountQuery.setString(9, item.getLocation());
			// addAccountQuery.setBlob(8, (Blob) item.getLocation());

			if (!addAccountQuery.execute()) {
				if (addAccountQuery.getUpdateCount() == 0) {
					success = false;
				}
			}
		} catch (SQLException e) {
			success = false;
			System.err.println(e);
		}

		return success;
	}

}
